package fr.n7.khome.view.editors;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;

import fr.n7.khome.core.Fuzzy;
import fr.n7.khome.util.FuzzyFormatException;
import fr.n7.khome.util.InvalidFuzzyValueException;


public class FuzzyTextEditor extends AbstractCellEditor implements TableCellEditor, KeyListener{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5740771874458938144L;
	public JTextField textField;
	public Fuzzy value;
	
	public FuzzyTextEditor(){
		super();
		textField = new JTextField("?");
		textField.setHorizontalAlignment(JTextField.CENTER);
		textField.selectAll();
		textField.setBackground(new Color(200,200,250));
		value = Fuzzy.whateverFuzzy();
		textField.addKeyListener(this);
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value,
			boolean isSelected, int row, int column) {
		this.value = (Fuzzy)value;
		textField.setText(value.toString());
		textField.selectAll();
		return textField;
	}
	
	@Override
	public boolean stopCellEditing(){
		Fuzzy f = null;
		String stringFuzzy = textField.getText();
		if(stringFuzzy.equals("")){
			textField.setText(value.toString());
			return false;
		}else{
			try {
				f = Fuzzy.parse(stringFuzzy);
			} catch (FuzzyFormatException e) {
				textField.setText(value.toString());
				return false;
			} catch (InvalidFuzzyValueException e) {
				textField.setText(value.toString());
				return false;
			}
		}
		value = f;
		textField.setText(value.toString());
		fireEditingStopped();
		return true;
	}
	
	@Override
	public Object getCellEditorValue() {
		return value;
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		boolean error = false;
		try {
			Fuzzy.parse(textField.getText());
		} catch (FuzzyFormatException e) {
			error = true;
		} catch (InvalidFuzzyValueException e) {
			error = true;
		} catch (NumberFormatException e){
			error = true;
		}
		if(error){
			textField.setForeground(Color.red);
		}else{
			textField.setForeground(Color.black);
			
		}
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
	}
	
}
